package com.eternal.widget.guqiang;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.eternal.framework.utils.ConvertUtils;
import com.eternal.framework.utils.Utils;
import com.eternal.widget.R;

/**
 * Created by Administrator
 * On 2020/5/7
 * Description:
 *
 * @author Administrator
 */
public class SingleCloseProgressBar extends ConstraintLayout implements IEffectBar {
    private IEffectBar.Listener listener;
    private IEffectBar.Factory factory;
    private TextView title, minTitle, maxTitle, show;
    private ImageView circle;
    private View progress, progressBack;
    private Switch s;
    private int width, cWidth;
    private boolean isMax;
    private int min, distance, interval, now;
    private float px;
    private float dWidth;

    public SingleCloseProgressBar(Context context) {
        this(context, null);
    }

    public SingleCloseProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SingleCloseProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View view = View.inflate(context, R.layout.layout_single_close_progressbar, this);
        title = view.findViewById(R.id.txt_title);
        show = view.findViewById(R.id.txt_show);
        circle = view.findViewById(R.id.img_circle);
        progress = view.findViewById(R.id.v_progress);
        progressBack = view.findViewById(R.id.v_progress_background);
        minTitle = view.findViewById(R.id.txt_min);
        maxTitle = view.findViewById(R.id.txt_max);
        s = view.findViewById(R.id.sw_close);
        s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    show.setTextColor(ContextCompat.getColor(Utils.getContext(), R.color.color_15BAFF));
                    progressBack.setBackgroundResource(R.drawable.rectang_10_ffffff_shape);
                    progress.setVisibility(VISIBLE);
                } else {
                    show.setTextColor(ContextCompat.getColor(Utils.getContext(), R.color.color_5D5D5D));
                    progressBack.setBackgroundResource(R.drawable.rectang_10_eeeeee_shape);
                    progress.setVisibility(INVISIBLE);
                }
                if (listener != null) {
                    listener.onChecked(isChecked);
                }
            }
        });

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SingleCloseProgressBar);
        title.setText(array.getString(R.styleable.SingleCloseProgressBar_title));
        distance = array.getInt(R.styleable.SingleCloseProgressBar_distance, 0);
        min = array.getInt(R.styleable.SingleCloseProgressBar_minNum, 0);
        minTitle.setText(array.getString(R.styleable.SingleCloseProgressBar_minTitle));
        maxTitle.setText(array.getString(R.styleable.SingleCloseProgressBar_maxTitle));
        interval = array.getInt(R.styleable.SingleCloseProgressBar_interval, 1);
        isMax = array.getBoolean(R.styleable.SingleCloseProgressBar_isMax, false);
        array.recycle();
    }


    @Override
    public void setListener(Listener listener) {
        this.listener = listener;
    }

    /**
     * 是否按到了view上
     *
     * @param ev
     * @return
     */
    private boolean inRangeOfView(MotionEvent ev) {
        int[] location = new int[2];
        circle.getLocationOnScreen(location);
        float ivBarX = circle.getX();
        float ivBarY = circle.getY();
        float left = ivBarX - ConvertUtils.dp2px(30);
        float right = ivBarX + cWidth + ConvertUtils.dp2px(30);
        float bottom = ivBarY + circle.getMeasuredHeight();
        Rect rect = new Rect((int) left, (int) ivBarY, (int) right, (int) bottom);
        return rect.contains((int) ev.getX(), (int) ev.getY());
    }

    public void setType(String title, String minStr, String maxStr, int min, int distance) {
        this.title.setText(title);
        setValue(minStr, maxStr, min, distance);
    }

    public void setValue(String minStr, String maxStr, int min, int distance) {
        this.minTitle.setText(minStr);
        this.maxTitle.setText(maxStr);
        this.min = min;
        this.distance = distance;
    }

    @Override
    public void setFactory(Factory factory) {
        this.factory = factory;
        int max = width - cWidth;
        show.setText(factory.getText((int) (circle.getTranslationX() * distance / max + min)));
    }

    @Override
    public void setProgress(float x, boolean isMax) {
        if (x == -1) {
            px = width - cWidth;
        } else {
            px = x;
        }
        this.isMax = isMax;
        moveProgress(circle.getTranslationX());
    }

    @Override
    public float getTx() {
        return circle.getTranslationX();
    }

    public void setProgress(int value) {
        float x = (value - min) * dWidth + cWidth / 2f;
        moveView(x);
        now = value;
        if (listener != null) {
            listener.onChange(value);
        }
    }

    @Override
    public int getProgress() {
        return now;
    }

    /**
     * 移动滑块
     */
    private void moveView(float x) {
        int max = width - cWidth;
        x -= cWidth / 2f;
        x = (x < 0 ? 0 : (x > max ? max : x));
        //当前移动的长度换算成显示文字
        now = Math.round(x / dWidth + min);
        if (factory != null) {
            show.setText(factory.getText(now));
        } else {
            show.setText(String.valueOf(now));
        }
        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        show.measure(spec, spec);
        circle.setTranslationX(x);
        int tvShowTextWidth = show.getMeasuredWidth();
        float mCurrentIvBarX = circle.getX();
        if (mCurrentIvBarX == 0) {
            show.setTranslationX(0);
        } else {
            float tvshowTextX = mCurrentIvBarX + cWidth / 2f - tvShowTextWidth / 2f;
            show.setTranslationX(tvshowTextX < 0 ? 0 : tvshowTextX + tvShowTextWidth > width ? width - tvShowTextWidth : tvshowTextX);
        }
        moveProgress(x);
    }

    //update  高低温和高低湿相同时，将显示两边区域，改为：显示中间区域
    private void moveProgress(float x) {
        if (isMax) {
//            if (x > px || now == Math.round(px / dWidth + min)) {
            if (x > px && now != Math.round(px / dWidth + min)){
                x = width - x;
            } else {
                x = px - x + cWidth;
            }
            x = (int) x;
            if (x == 0) {
                x = width - circle.getTranslationX();
            }
            progress.setTranslationX(circle.getTranslationX());
            ViewGroup.LayoutParams params = progress.getLayoutParams();
            params.width = (int) x;
            progress.setLayoutParams(params);
        } else {
//            if (x > px && now != Math.round(px / dWidth + min)) {
            if (x > px || now == Math.round(px / dWidth + min)) {
                x = x - px;
                progress.setTranslationX(px);
            } else {
                progress.setTranslationX(0);

            }
            x = (int) x;
//            if (x == 0) {
            if (x <= 0) {
                x = 1;
            }
            ViewGroup.LayoutParams params = progress.getLayoutParams();
            params.width = (int) x;
            progress.setLayoutParams(params);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                getParent().requestDisallowInterceptTouchEvent(true);
                if (!inRangeOfView(event)) {
                    return false;
                }
                if (null != listener) {
                    listener.onDown(true);
                }
                if (!s.isChecked()) {
                    s.setChecked(true);
                    if (listener != null) {
                        listener.onChecked(true);
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                moveView(x);
                if (null != listener) {
                    listener.onChange(now);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (null != listener) {
                    listener.onUp(true, now);
                }
            case MotionEvent.ACTION_CANCEL:
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
            default:
        }
        return true;
    }

    public void setChecked(boolean b) {
        s.setChecked(b);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = progressBack.getMeasuredWidth();
        cWidth = circle.getMeasuredWidth();
        dWidth = (width - cWidth) / ((float) distance);
        if (isMax) {
            setProgress(-1, isMax);
        } else {
            setProgress(0, isMax);
        }
        post(new Runnable() {
            @Override
            public void run() {
                float x = (now - min) * dWidth + cWidth / 2f;
                moveView(x);
                if (listener != null) {
                    listener.onChange(now);
                }
            }
        });

    }

    @Override
    public boolean isChecked() {
        return s.isChecked();
    }
}
